<!--
 * @Author: Haochen
 * @Date: 2021-12-07 17:37:29
 * @LastEditTime: 2022-01-02 18:53:16
 * @FilePath: \recipes-admin-system\src\views\members\Members.vue
-->
<template>
  <div class="members-container">
    <bread-crumb></bread-crumb>

    <div class="search-area">
      <el-input type="text" v-model="searchValue"> </el-input>
      <el-button type="primary" @click="searchMember">搜索</el-button>

      <!-- <el-button type="primary" @click="addDialogVisible = true">
        <i class="el-icon-circle-plus-outline"></i> 添加
      </el-button> -->
    </div>

    <el-table
      :data="membersByPage"
      border
      style="width: 100%"
      :header-cell-style="rowClass"
      :cell-style="rowClass"
      :stripe="true"
      :highlight-current-row="true"
    >
      <el-table-column label="'用户编号">
        <template slot-scope="scope">
          <span>{{ scope.row._id.substr(-5) }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="nickName" label="用户名"> </el-table-column>

      <el-table-column label="头像">
        <template slot-scope="scope">
          <img :src="scope.row.avatarUrl" alt="" />
        </template>
      </el-table-column>

      <el-table-column label="住址">
        <template slot-scope="scope">
          {{ scope.row.province | provinceFilter }}
        </template>
      </el-table-column>

      <el-table-column label="VIP截止时间">
        <template slot-scope="scope">
          {{ scope.row.vipdate | vipDateFilter }}
        </template>
      </el-table-column>

      <!-- v-auth -->

      <el-table-column label="操作" width="375">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="openMemberDialog(scope.row._id)"
          >
            <i class="el-icon-money"></i> 充值会员
          </el-button>

          <el-button
            size="mini"
            type="danger"
            @click="cancelMember(scope.row._id)"
          >
            <i class="el-icon-warning-outline"></i> 取消会员</el-button
          >

          <el-button
            size="mini"
            type="danger"
            @click="deleteMember(scope.row._id)"
          >
            <i class="el-icon-circle-close"></i> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      width="500px"
      :append-to-body="true"
      title="升级会员"
      :visible.sync="memberDialogVisible"
      :before-close="handleClose"
    >
      <span>请选择您充值会员的终止日期(必须大于等于今天)</span>
      <br />
      <br />

      <el-date-picker
        value-format="yyyy-MM-dd"
        v-model="date"
        type="date"
        placeholder="选择日期"
      >
      </el-date-picker>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>

        <el-button
          type="primary"
          :disabled="!isVipDateValid"
          @click="updateMemberToVip"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <pages
      :total="total"
      :currentPage="pageData.currentPage"
      :pageSize="pageData.pageSize"
      @prevPage="prevPage"
      @nextPage="nextPage"
    />
  </div>
</template>

<script>
import Pages from '../../components/common/Pages.vue';
import BreadCrumb from '../../components/common/BreadCrumb.vue';

import bus from '@/utils/bus.js';
import pageMixin from '@/mixins/pageMixin';

import { createNamespacedHelpers } from 'vuex';

function compareDate(d1, d2) {
  return new Date(d1.replace(/-/g, '\/')) > new Date(d2.replace(/-/g, '\/'));
}

const {
  mapActions: membersActions,
  mapState: membersState,
  mapMutations: membersMutations,
  mapGetters: membersGetters,
} = createNamespacedHelpers('members');

export default {
  mixins: [pageMixin],
  components: {
    pages: Pages,
    'bread-crumb': BreadCrumb,
  },
  data() {
    return {
      formLabelWidth: '120px',
      searchValue: '',
      memberDialogVisible: false,
      memberId: '',
      date: '',
      isVipDateValid: false,
    };
  },
  computed: {
    ...membersState(['members', 'total', 'pages']),
    ...membersGetters(['membersByPage']),
  },
  created() {
    this.getAllMembers();

    bus.$on('handleSizeChange', (size) => {
      this.pageData.pageSize = size;
      this.getAllMembers();
    });

    bus.$on('handleCurrentChange', (currentPage) => {
      this.pageData.currentPage = currentPage;
      this.getAllMembers();
    });
  },
  methods: {
    ...membersActions(['getAllMembersAsync']),
    ...membersMutations(['SET_PAGESIZE', 'SET_CURRENT']),

    async getAllMembers(searchValue) {
      this.getAllMembersAsync(searchValue);
      this.SET_PAGESIZE(this.pageData.pageSize);
      this.SET_CURRENT(this.pageData.currentPage);
      //   console.log(this.$store.state);
      //   console.log(this.admins);
    },

    rowClass() {
      return 'text-align:center';
    },

    openMemberDialog(id) {
      this.memberDialogVisible = true;
      this.memberId = id;
    },

    async deleteMember(id) {
      this.$confirm('此操作将永久删除会员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let _id = { _id: id };

          let { data: res } = await this.$api.members.deleteMember(_id);
          // console.log(res);
          if (res.meta.status === 200) {
            // this.$message({
            //   message: res.meta.msg,
            //   type: 'success',
            // });

            this.$notify({
              title: '成功',
              message: res.meta.msg,
              type: 'success',
            });
            this.getAllMembers();
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },

    async cancelMember(id) {
      this.$confirm('此操作将取消此会员的vip权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let _id = { _id: id };
          let { data: res } = await this.$api.members.cancelMember(_id);
          // console.log(res);
          if (res.meta.status === 200) {
            this.$notify({
              title: '成功',
              message: '取消会员成功',
              type: 'success',
            });
            // this.$message({
            //   message: '取消会员成功',
            //   type: 'success',
            // });
            this.getAllMembers();
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作',
          });
        });
    },

    async updateMemberToVip() {
      let memberInfo = {
        _id: this.memberId,
        date: this.$moment(this.date).format('MM/DD/YYYY'),
      };
      console.log(memberInfo);

      let { data: res } = await this.$api.members.updateMemberToVip(memberInfo);

      if (res.meta.status === 200) {
        this.$notify({
          title: '成功',
          message: '升级会员成功',
          type: 'success',
        });
      }

      // this.$message({
      //   message: '升级会员成功',
      //   type: 'success',
      // });
      this.memberDialogVisible = false;
      this.getAllMembers();
    },

    searchMember() {
      this.getAllMembers(this.searchValue);
    },

    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          this.singleMenuItem = {};
          done();
        })
        .catch((_) => {});
    },

    closeDialog() {
      this.memberDialogVisible = false;
      this.date = '';
    },
  },
  watch: {
    pageData: {
      handler(val) {
        this.getAllMembers();
      },
      deep: true,
    },

    'pageData.pageSize'() {
      this.pageData.currentPage = 1;
      this.getAllMembers();
    },

    searchValue(val) {
      if (!val) {
        this.getAllMembers(val);
      }
    },

    date(selectDate) {
      let currentDate = this.$moment().format('YYYY-MM-DD');

      let isDateValid = compareDate(selectDate, currentDate);
      console.log(isDateValid);
      if (isDateValid) {
        this.isVipDateValid = true;
      } else {
        this.isVipDateValid = false;
        this.$message.error('充值会员的时间，必须大于等于当前时间才能确认');
      }
    },
  },
};
</script>

<style scoped lang="scss">
// @import '@/assets/sass/common.scss';

a {
  text-decoration: none;
  color: rgb(124, 124, 124);
}

.members-container {
  width: 100%;
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  box-sizing: border-box;
  table {
    margin: 20px 0;
    width: 100%;
    text-align: center;
    border: 1px solid #ccc;
    border-collapse: collapse;
    tr td,
    th {
      height: 50px;
      border: 1px solid #ccc;
      img {
        width: 50px;
        height: 50px;
        border-radius: $vue-border-radius-base;
      }
    }
  }
}

.search-area {
  margin-bottom: 30px;
  height: 30px;
  .el-input {
    width: 200px;
    height: 30px;
    margin-right: 10px;
  }
}

.el-input {
  width: 70%;
}
</style>
